<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>盘点管理</title>
	<meta name="renderer" content="webkit">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
	<jsp:include page="${pageContext.request.contextPath }/resource_path.jsp" flush="true"/>
</head>
<body class="layui-anim layui-anim-up">
    <div class="x-nav">
      <span class="layui-breadcrumb">
        <a href="">首页</a>
        <a>
          <cite>盘点单导入</cite>
        </a>
      </span>
    </div>
    <div class="x-body">
      <div style="margin-bottom: 18px">
		<div class="layui-inline">
			<table>
				<tr>
					<td>
						<div class="layui-form" style="width: 180px; margin-left: 10px">
							<select id="keyword01" name="keyword" lay-filter="keyword01">
								<option value="">请选择盘点类型</option>
								<option value="月盘点">月盘点</option>
								<option value="年盘点">年盘点</option>
								<option value="周盘点">周盘点</option>
								<option value="日盘点">日盘点</option>
							</select>
						</div>
					</td>
					<%--
					<td>
						<div class="layui-form" style="width: 180px; margin-left: 10px">
							<select id="keyword2" name="keyword" lay-filter="orderNumber">
								<option value="">请选择收货方</option>
								<option>收货方一</option>
								<option>收货方二</option>
								<option>收货方三</option>
							</select>
						</div>
					</td>
					--%>
				</tr>
			</table>
		</div>
		<button class="layui-btn layui-btn-normal" data-type="reload"><i class="layui-icon">&#xe615;</i>检索</button>
	  </div>
      <xblock>
			<button id="add" class="layui-btn layui-btn-warm"><i class="layui-icon"></i>新增盘点单</button>
			<button id="dels" class="layui-btn layui-btn-danger"><i class="layui-icon layui-icon-delete"></i>批量删除</button>
      </xblock> 
	  <table class="layui-hide" id="tableList" lay-filter="tableList"></table>
	  <!-- <table class="layui-hide" id="tableListSub" lay-filter="tableListSub"></table> -->
	</div>
	<div id="subTable" hidden="hidden">
	
	<input type="hidden"  id="orid"></input>
		<xblock>
			<button id="add1" class="layui-btn layui-btn-warm"><i class="layui-icon layui-icon-add-circle-fine"></i>选择物料</button>
			<button id="dels1" class="layui-btn layui-btn-danger"><i class="layui-icon layui-icon-delete"></i>批量删除</button>
	  </xblock>
	  <table class="layui-hide" id="tableListSub" lay-filter="tableListSub"></table>
	</div>
	
	<script type="text/html" id="rowToolbar">
		<a class="layui-btn layui-btn-xs" lay-event="detail"><i class="layui-icon layui-icon-edit"></i>盘点单详细调整</a>
		<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del1"><i class="layui-icon layui-icon-delete"></i>删除</a>
	</script>
	<script type="text/html" id="rowToolbar2">
		<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del2">删除</a>
	</script>

	<script type="text/javascript">
        var table;
		layui.use(['table','layer','upload','form','laydate'], function(){
			table = layui.table;
			var layer = layui.layer;
			var form = layui.form;
			var laydate = layui.laydate;
			var $ = layui.jquery, active = {
				reload:function () {
					var keyword01 = $("#keyword01").val();
					table.reload('contenttable',{
						method:'get',
						where:{"keyword01":keyword01}
					});
				}
			}
			$('.layui-btn').on('click', function(){
				var type = $(this).data('type');
				active[type] ? active[type].call(this) : '';
			});
			table.render({
				elem: '#tableList'
				,url:'${pageContext.request.contextPath }/inventory/queryInventoryOrderCriteria.do'
				,toolbar: '#toolbar'
				,title: 'machineList'
				,id :'contenttable'
				,limits:[10,20,30]
                ,defaultToolbar:['filter', 'print']
				,cols: [[
				  {type: 'checkbox', fixed: 'left', },
				  {field:'', title:'序号', width: 50, /* sort: true,  */type:'numbers', align:'center'},
				  {field:'inventory_order_num', title:'盘点单号', align:'center'},
				  {field:'inventory_type', title:'盘点类型', align:'center'},
				  {field:'userName', title:'盘点人员', align:'center'},
				  {field:'inventory_time', title:'盘点日期', align:'center'},
				  //{field:'warehouse_name', title:'盘点仓库', align:'center'},
				  
				  //{fixed:'right', unresize: true, title:'操作', toolbar: '#rowToolbar', align:'center',width: 200}
				]]
				,page: true
                ,done : function(){
                    $(".timepicker").each(function () {
                        laydate.render({
                            elem: this,
                            format: "yyyy-MM-dd"
                        });
                    });
                    $('th').css({
                        'background-color': '#009688', 'color': '#fff','font-weight':'bold',
                    })
                }
			});

			//行单击事件
			table.on('row(tableList)', function(obj) {
				$("#subTable").show();
               	var data = obj.data;
               	console.log(data.id);
               	$("#orid").val(data.id);
                table.render({
                	elem: '#tableListSub'
                   ,url:'${pageContext.request.contextPath }/inventory/queryInventoryDetailCriteriaById.do?keyword01='+data.id
                   ,toolbar: '#toolbar'
                   ,title: 'machineList'
                   ,id :'contenttable1'
                   ,limits:[10,20,30]
                   ,defaultToolbar:['filter', 'print']
                   ,cols: [[
                       {type: 'checkbox', fixed: 'left'},
                       {field:'id1', title:'序号', width: 100, fixed: 'left', unresize: true, sort: true, type:'numbers'},
                       {field:'id', title:'ID', align:'center', hide:true}, //隐藏不显示
                       {field:'customer_id', title:'供应商ID', align:'center', hide:true}, //隐藏不显示
                       {field:'customer_name', title:'供应商名称', align:'center'}, //隐藏不显示
                       {field:'region_name', title:'库区名称', align:'center'}, //隐藏不显
                       //{field:'customer_name', title:'供应商名称', align:'center'},
                       {field:'materiel_id', title:'物料ID', align:'center', hide:true}, //隐藏不显示
                       {field:'materiel_name', title:'物料名称', align:'center'},
                       {field:'materiel_num', title:'物料编码', align:'center'},
                       {field:'materiel_size', title:'物料规格', align:'center'},
                       {field:'materiel_properties', title:'物料型号', align:'center'},
                       {field:'unit', title:'单位', align:'center'},
					{field:'theoretical_quantity', title:'库存数量', align:'center'},
                       {field:'actual_quantity', title:'实际数量', align:'center', edit: true, templet: function (row){
						return '<span style="color: blue">'+row.actual_quantity+'</span>';
					}},
					{field:'difference_quantity', title:'差异数量', align:'center'},
                       //{fixed:'right', title:'操作', toolbar: '#rowToolbar2', width: 80, align:'center'}
                   ]]
                   ,page: true
                   ,done : function(){
                       $('th').css({
                           'background-color': '#009688', 'color': '#fff','font-weight':'bold',
                       })
                   }
               });
           });

		var ids =new Array();
        //当前表格中的全部数据:在表格的checkbox全选的时候没有得到数据, 因此用全局存放变量
        var table_data=new Array()
		table.on('checkbox(materielTable)', function (obj) {
           if(obj.checked==true){
               if(obj.type=='one'){
                   ids.push(obj.data.id);
              }else{
                   for(var i=0;i<table_data.length;i++){
                       ids.push(table_data[i].id);
                   }
               }
           }else{
               if(obj.type=='one'){
                   for(var i=0;i<ids.length;i++){
                      if(ids[i]==obj.data.id){
                           ids.remove(i);
                       }
                  }
               }else{
                   for(var i=0;i<ids.length;i++){
                       for(var j=0;j<table_data.length;j++){
                           if(ids[i]==table_data[j].id){
                              ids.remove(i);
                          }
                       }
                   }
               }
           }
           for(var i=0;i<ids.length;i++){
           		console.log("*******************"+ids[i].id)
           }
        });
            //"盘点单"的行内编辑事件
            table.on('edit(tableList)', function(obj){
                var fieldValue = obj.value, 		//得到修改后的值
                    rowData = obj.data, 			//得到所在行所有键值
                    fieldName = obj.field; 			//得到字段
                	layui.use('jquery',function(){
                    var $=layui.$;
                    $.ajax({
                        type: "post",
                        url: "${pageContext.request.contextPath }/inventory/updateInventoryOrderById.do",
                        data: { id:rowData.id, fieldName:fieldName, fieldValue:fieldValue, theoretical_quantity:rowData.theoretical_quantity},
                        success: function(data){
                        	toastr.success("修改成功！");
                            location.reload();
                        }
                    });
                });
            });

            //"盘点单详细"的行内编辑事件
            table.on('edit(tableListSub)', function(obj){
                var fieldValue = obj.value, 	//得到修改后的值
                    rowData = obj.data, 		//得到所在行所有键值
                    fieldName = obj.field; 
               		//得到字段
                	layui.use('jquery',function(){
                    var $=layui.$;
                    $.ajax({
                        type: "post",
                        url: "${pageContext.request.contextPath }/inventory/updateInventoryOrderDetailById.do",
                        data: { mid:rowData.materiel_id, fieldName:fieldName, fieldValue:fieldValue,cid:rowData.customer_id ,detailid:rowData.id},
                        success: function(data){
                        	toastr.success("修改成功！");
                            location.reload();
                        }
                    });
                });
            });

            //"盘点单详细"的行内删除事件
            table.on('tool(tableListSub)', function(obj2){
                layer.confirm('确定删除吗？', function(index){
                    var id = obj2.data.id;
                    $.ajax({
                        type:'post',
                        url:'${pageContext.request.contextPath }/inventory/deleteInventoryOrderDetailById.do',
                        data:{ "id" : id },
                        success:function(data){
                            if(data > 0){
                                toastrStyle();
                                toastr.success("删除成功！");
                                setTimeout(function(){
                                    location.reload();
                                },1000);
                            }else{
                                toastrStyle();
                                toastr.error("删除失败！");
                                setTimeout(function(){
                                    location.reload();
                                },1000);
                            }
                        }
                    });
                    layer.close(index);
                });
            });

			/**
			 * 添加弹框中，选择物料后，点提交，带回的操作
			 */
			form.on('submit(productform)', function (data) {
				var checkStatus = table.checkStatus('materielTable')
	      		var data = checkStatus.data;
				var b;
				for (var i = 0; i < data.length; i++) {
					console.log("************"+data[i].materiel_name)
				 	
                   	var val02 = data[i].id == null?"":data[i].id;
                   	
                   	$("#myTable").find("tr").each(function(){
                    	var tdArr = $(this).children();
                       	var h = tdArr.eq(0).text();
                       	if(h==val02){
                       		b=0;
                       		//toastr.warning("记录已经存在，不能重复添加")
                        }
                 	})
				 }
                 if(b!=0){
              		var checkStatus = table.checkStatus('materielTable')
  		      		var data = checkStatus.data;
  					 for (var i = 0; i < data.length; i++) {
  						 //console.log("************"+data[i].materiel_name)
  						 var val01 = data[i].materiel_name == null?"":data[i].materiel_name;
  		                    var val05 = data[i].materiel_num == null?"":data[i].materiel_num;
  		                    var val06 = data[i].brevity_num == null?"":data[i].brevity_num;
  		                    var val07 = data[i].customer_name == null?"":data[i].customer_name;
  		                    var val02 = data[i].id == null?"":data[i].id;
  		                    var val08 = data[i].customer_id == null?"":data[i].customer_id;
  		                  var val03 = data[i].materiel_size == null?"":data[i].materiel_size;
  		                var val04 = data[i].materiel_properties == null?"":data[i].materiel_properties;
  							$("#myTable tbody").append('<tr >'+
  								'<td style="display:none">'+val02+'</td>'+
  								'<td style="display:none">'+val08+'</td>'+
  								'<td>'+val07+'</td>'+
  								'<td>'+val01+'</td>'+
  								'<td>'+val05+'</td>'+
  								'<td>'+val06+'</td>'+
  								'<td>'+val03+'</td>'+
  								'<td>'+val04+'</td>'+
  								
  							'</tr>');
  						}
  		            layer.close(productIndex)
  					return false;
                 }else{
              	  //alert("记录已经存在，不能重复添加");	
              	  //setTimeout(function(){
				  //location.reload();
				  //},1000);
              	  toastrStyle();
              	  toastr.warning("记录已经存在，不能重复添加")
              	  //layer.open(productIndex)
  				 return false;
              	 }
	        });
			 $(document).on('click','#btn',function(){
				 productIndex= layer.open({
		                type: 1 					//Page层类型
		                ,area: ['900px', '450px'] 	//宽  高
		                ,title: '物料清单'
		                ,shade: 0.6 				//遮罩透明度
		                ,maxmin: true 				//允许全屏最小化
		                ,anim: 1 					//0-6的动画形式，-1不开启
		                ,content: '<form class="layui-form" onsubmit="return false">' +
			               '<div style="margin-bottom: 18px" width="550px"  class="demoTable">'+
			        		'<div class="layui-inline">'+
			        			'<table align="center">'+
			        				'<tr>'+
			        					'<td>供应商</td>'+
			        					'<td>&nbsp&nbsp&nbsp</td>'+
			        					'<td>  <input type="text" name="gys" id="gys"  placeholder="请输入供应商" autocomplete="off" class="layui-input"></td>'+
			        					'<td>&nbsp&nbsp&nbsp</td>'+
			        					'<td>物料名称</td>'+
			        					'<td>&nbsp&nbsp&nbsp</td>'+
			        					'<td>  <input type="text" name="wlmc" id="wlmc"  placeholder="请输入物料名称" autocomplete="off" class="layui-input"></td>'+
			        					'<td>&nbsp&nbsp&nbsp</td>'+
			        					'<td>物料编码</td>'+
			        					'<td>&nbsp&nbsp&nbsp</td>'+
			        					'<td>  <input type="text" name="wlbm" id="wlbm"  placeholder="请输入物料编码" autocomplete="off" class="layui-input"></td>'+
			        				'</tr>'+
			        			'</table>'+
			        		'</div>'+
			        		'<button class="layui-btn"id="ido" data-type="reload">检索</button>'+
			        	  '</div>'+
			                '<table id="materielTable" lay-filter="materielTable"></table>' +
											'&nbsp&nbsp&nbsp'+
											 '<button class="layui-btn layui-btn-blue" lay-submit lay-filter="productform" style="margin: 0px 0px 10px 200px; width: 500px">提交</button>'+
									  '</form>'
		                ,success: function () {
		                    table.render({
		                        elem: '#materielTable'
		                        ,url:'${pageContext.request.contextPath }/inventory/findAllMateriel.do?'
		                        ,limits:[10,20,30]
		                        ,defaultToolbar:['filter', 'print']
		                        ,cols: [[
		           					{type: 'checkbox', fixed: 'left'}
		           					,{field:'xuhao', title:'序号', sort: true, type:'numbers', width: 60}
		           					//,{field:'id', title:'物料ID', align:'center', hide:true} //隐藏不显示
		           					,{field:'customer_id', title:'供应商ID', align:'center', hide:true} //隐藏不显示
		           					,{field:'customer_name', title:'供应商名称',templet:function(row){
		           						if(row.customer_name!=null){
		           							return row.customer_name;
		           						}else{
		           							return "";
		           						}
		           					}}
		           					,{field:'materiel_name', title:'物料名称',templet:function(row){
		           						if(row.materiel_name!=null){
		           							return row.materiel_name;
		           						}else{
		           							return "";
		           						}
		           					}}
		           					,{field:'materiel_num', title:'物料编号',templet:function(row){
		           						if(row.materiel_num!=null){
		           							return row.materiel_num;
		           						}else{
		           							return "";
		           						}
		           					}}
		           					,{field:'materiel_size', title:'物料规格',templet:function(row){
		           						if(row.materiel_size!=null){
		           							return row.materiel_size;
		           						}else{
		           							return "";
		           						}
		           					}}
		           					,{field:'materiel_properties', title:'物料型号',templet:function(row){
		           						if(row.materiel_properties!=null){
		           							return row.materiel_properties;
		           						}else{
		           							return "";
		           						}
		           					}}
		           					
		           				]]
		                        ,page: true
		                        ,done : function(){
		                            $('th').css({
		                                'background-color': '#009688', 'color': '#fff','font-weight':'bold',
		                            })
		                        }
		                    });
		                }
		            });
			 });
			 
			 $(document).on('click','#ido',function(){
				 var gys=$('#gys').val();
				 var wlmc=$('#wlmc').val();
				 var wlbm=$('#wlbm').val();
				    var table = layui.table;
			        table.reload('materielTable', {
			           

			            method:'post',
			            where:{"customer_name":gys,"materiel_name":wlmc,"materiel_num":wlbm
			                
			            },
			            done:function (res) {
			            	  $('th').css({
	                                'background-color': '#009688', 'color': '#fff','font-weight':'bold',
	                            })
			            }
			        });
			 }) 
	
    		$('#add1').click(function(){
    			 productIndex= layer.open({
		                type: 1 					//Page层类型
		                ,area: ['900px', '450px'] 	//宽  高
		                ,title: '物料清单'
		                ,shade: 0.6 				//遮罩透明度
		                ,maxmin: true 				//允许全屏最小化
		                ,anim: 1 					//0-6的动画形式，-1不开启
		                ,content: '<form class="layui-form" onsubmit="return false">' +
			               '<div style="margin-bottom: 18px" width="550px"  class="demoTable">'+
			        		'<div class="layui-inline">'+
			        			'<table align="center">'+
			        				'<tr>'+
			        					'<td>供应商</td>'+
			        					'<td>&nbsp&nbsp&nbsp</td>'+
			        					'<td>  <input type="text" name="gys" id="gys"  placeholder="请输入供应商" autocomplete="off" class="layui-input"></td>'+
			        					'<td>&nbsp&nbsp&nbsp</td>'+
			        					'<td>物料名称</td>'+
			        					'<td>&nbsp&nbsp&nbsp</td>'+
			        					'<td>  <input type="text" name="wlmc" id="wlmc"  placeholder="请输入物料名称" autocomplete="off" class="layui-input"></td>'+
			        					'<td>&nbsp&nbsp&nbsp</td>'+
			        					'<td>物料编码</td>'+
			        					'<td>&nbsp&nbsp&nbsp</td>'+
			        					'<td>  <input type="text" name="wlbm" id="wlbm"  placeholder="请输入物料编码" autocomplete="off" class="layui-input"></td>'+
			        				'</tr>'+
			        			'</table>'+
			        		'</div>'+
			        		'<button class="layui-btn"id="ido" data-type="reload">检索</button>'+
			        	  '</div>'+
			                '<table id="materielTable" lay-filter="materielTable"></table>' +
											'&nbsp&nbsp&nbsp'+
											 '<button class="layui-btn layui-btn-blue" lay-submit lay-filter="productform1" style="margin: 0px 0px 10px 200px; width: 500px">提交</button>'+
												'<table class="layui-table" id="myTable">' +
												'<thead style="text-align: center">'+
													'<tr style="background: #009688; color: white; align: center" >'+
														
														'<th style="display:none">物料ID</th>'+
														'<th style="display:none">供应商ID</th>'+
														'<th style="text-align:center;">供应商名称</th>'+
														'<th style="text-align:center;"}">物料名称</th>'+
														'<th style="text-align:center;"}">产品码</th>'+
														'<th style="text-align:center;"}">简码</th>'+
														'<th style="text-align:center;"}">物料规格</th>'+
														'<th style="text-align:center;"}">物料型号</th>'+
														
													'</tr>'+
												'</thead>'+
												'<tbody id="tbody" style="text-align: center;">'+
				                    			'</tbody>'+
											'</table>'+
											'<div align="center">'+
											'<xblock  align="center">'+
												'<button class="layui-btn layui-btn-blue" id="subBtn1" lay-submit lay-filter="addForm1" style="">提交</button>'+
											'</xblock>'+
											'</div>'+
											 '</form>'
		                ,success: function () {
		                    table.render({
		                        elem: '#materielTable'
		                        ,url:'${pageContext.request.contextPath }/inventory/findAllMateriel.do?'
		                        ,limits:[10,20,30]
		                        ,defaultToolbar:['filter', 'print']
		                        ,cols: [[
		           					{type: 'checkbox', fixed: 'left'}
		           					,{field:'xuhao', title:'序号', sort: true, type:'numbers', width: 60}
		           					//,{field:'id', title:'物料ID', align:'center', hide:true} //隐藏不显示
		           					,{field:'customer_id', title:'供应商ID', align:'center', hide:true} //隐藏不显示
		           					,{field:'customer_name', title:'供应商名称',templet:function(row){
		           						if(row.customer_name!=null){
		           							return row.customer_name;
		           						}else{
		           							return "";
		           						}
		           					}}
		           					,{field:'materiel_name', title:'物料名称',templet:function(row){
		           						if(row.materiel_name!=null){
		           							return row.materiel_name;
		           						}else{
		           							return "";
		           						}
		           					}}
		           					,{field:'materiel_num', title:'物料编号',templet:function(row){
		           						if(row.materiel_num!=null){
		           							return row.materiel_num;
		           						}else{
		           							return "";
		           						}
		           					}}
		           					,{field:'materiel_size', title:'物料规格',templet:function(row){
		           						if(row.materiel_size!=null){
		           							return row.materiel_size;
		           						}else{
		           							return "";
		           						}
		           					}}
		           					,{field:'materiel_properties', title:'物料型号',templet:function(row){
		           						if(row.materiel_properties!=null){
		           							return row.materiel_properties;
		           						}else{
		           							return "";
		           						}
		           					}}
		           					
		           				]]
		                        ,page: true
		                        ,done : function(){
		                            $('th').css({
		                                'background-color': '#009688', 'color': '#fff','font-weight':'bold',
		                            })
		                        }
		                    });
		                }
		            });
    		});
		
				form.on('submit(productform1)', function (data) {
					var checkStatus = table.checkStatus('materielTable')
		      		var data = checkStatus.data;
					var order_id = $('#orid').val();
					var b;
					var b1;
				
					  for (var i = 0; i < data.length; i++) {
							
		                   	var val02 = data[i].id == null?"":data[i].id;
		                  
		                 	//和已添加列表比较
		                 	//根据已知盘点id获取所有物料id，遍历比较
		                 	
		                 	  $.ajax({
		                                type:'post'
		                                ,url:'${pageContext.request.contextPath}/inventory/queryMidByOrder.do'
		                                ,data:{orderId:order_id, 
		                                	}
		                                ,dataType:'json'
		                                ,success:function(datas){
		                                	console.log(datas)
		                                  for(var i=0;i<datas.length;i++){
		                                  		
		                                	 var m=datas[i].materiel_id;
		                                	 console.log("_____________________--"+m)
		                                	  if(m==val02){
		                                		 toastrStyle();
		                    	              	  toastr.warning("记录已经添加，不能重复添加")
		                    	                  break; 
		                    	                  b1=0;
		                    	                  
		   	                                   }
		                                		
		                                	}
		                                 
		                                 }
		                            })
		                      
		             }
					  
			
					 if(b1!=0){
		
					  
                    for (var i = 0; i < data.length; i++) {
						
	                   	var val02 = data[i].id == null?"":data[i].id;
	                   	//和已提交列表比较
	                   	$("#myTable").find("tr").each(function(){
	                    	var tdArr = $(this).children();
	                       	var h = tdArr.eq(0).text();
	                       	if(h==val02){
	                       		b=0;
	                       		//toastr.warning("记录已经存在，不能重复添加")
	                        }
	                 	})
	                 	
	      		 }
					
				   if(b!=0){
	              		var checkStatus = table.checkStatus('materielTable')
	  		      		var data = checkStatus.data;
	  					 for (var i = 0; i < data.length; i++) {
	  						 //console.log("************"+data[i].materiel_name)
	  						 var val01 = data[i].materiel_name == null?"":data[i].materiel_name;
	  		                    var val05 = data[i].materiel_num == null?"":data[i].materiel_num;
	  		                    var val06 = data[i].brevity_num == null?"":data[i].brevity_num;
	  		                    var val07 = data[i].customer_name == null?"":data[i].customer_name;
	  		                    var val02 = data[i].id == null?"":data[i].id;
	  		                    var val08 = data[i].customer_id == null?"":data[i].customer_id;
	  		                  var val03 = data[i].materiel_size == null?"":data[i].materiel_size;
	  		                var val04 = data[i].materiel_properties == null?"":data[i].materiel_properties;
	  							$("#myTable tbody").append('<tr >'+
	  								'<td style="display:none">'+val02+'</td>'+
	  								'<td style="display:none">'+val08+'</td>'+
	  								'<td>'+val07+'</td>'+
	  								'<td>'+val01+'</td>'+
	  								'<td>'+val05+'</td>'+
	  								'<td>'+val06+'</td>'+
	  								'<td>'+val03+'</td>'+
	  								'<td>'+val04+'</td>'+
	  								
	  							'</tr>');
	  						}
	  		          //  layer.close(productIndex)
	  					return false;
	                 }else  {
	              	  //alert("记录已经存在，不能重复添加");	
	              	  //setTimeout(function(){
					  //location.reload();
					  //},1000);
	              	  toastrStyle();
	              	  toastr.warning("记录已经存在，不能重复添加")
	              	  //layer.open(productIndex)
	  				 return false;
	              	 
					}
					 }else{
							toastrStyle();
			              	  toastr.warning("记录已经存在，不能重复添加")
			            }
		        });
			
 
			
			
			
				form.on('submit(addForm1)', function (data) {
					
				
				 $("#tbody tr").each(function(i,dom){
                        var tr = $(dom).closest("tr");
                        var tds = tr.find("td");
          
                        var order_id = $('#orid').val();
                       
                        var materiel_id = tds.eq(0).html();
                        var cid= tds.eq(1).html();
                            $.ajax({
                            type:'post'
                            ,url:'${pageContext.request.contextPath}/inventory/addInventoryOrderDetail.do'
                            ,data:{order_id:order_id, 
                            	materiel_id:materiel_id,customer_id:cid}
                            ,dataType:'json'
                            ,success:function (res) {
                            	console.log(res)
		            		}
                        })
                       
                	}); 
				 toastrStyle();
					toastr.success('新增成功！');
					setTimeout(function(){
						location.reload();
					},1000);
				 return false;	

		})
		
		
			/**
			 * 通用表单提交(AJAX方式)(新增)
			 */
			form.on('submit(addForm)', function (data) {
				$.ajax({
					url : '${pageContext.request.contextPath}/inventory/addInventoryOrder.do',
					data: $("#addFormID").serialize(),
					cache : false,
					type : "post",
				}).done(
					function(res) {
						if (res > 0) {
							 console.log("**"+res);
							//如果父表新增成功再执行新增子表的操作
							$("#tbody tr").each(function(i,dom){
	                            var tr = $(dom).closest("tr");
	                            var tds = tr.find("td");
	                            //主表插入行ID
	                            var order_id = res;
	                           // var actual_quantity = tds.eq(3).html();
	                            //var theoretical_quantity = tds.eq(4).html();
	                           // var difference_quantity = tds.eq(5).html();
	                            var materiel_id = tds.eq(0).html();
	                            var cid= tds.eq(1).html();
	                            $.ajax({
	                                type:'post'
	                                ,url:'${pageContext.request.contextPath}/inventory/addInventoryOrderDetail.do'
	                                ,data:{order_id:order_id, 
	                                	materiel_id:materiel_id,customer_id:cid}
	                                ,dataType:'json'
	                                ,success:function(data){
	                                    console.log(data);
	                                }
	                            })
                        	});
							/* —————————————— */
							toastrStyle();
							toastr.success('新增成功！');
							setTimeout(function(){
								location.reload();
							},1000);
							/* —————————————— */
						}
					}
				).fail(
					function(res) {
						toastrStyle();
						toastr.error('新增失败！');
						setTimeout(function(){
							location.reload();
						},1000);
					}
				)
				return false;
			});

			/**
			 * 新增表单校验
			 */
			form.verify({
				//value：表单的值item：表单的DOM对象
				inventory_type: function(value, item){
					if(value == ''){
						return '盘点类型不能为空';
					}
				},
				
			});
			$("#dels1").click(function(){
				var rowData = table.checkStatus('contenttable1');
				var data = rowData.data;
				var idArr = new Array();
				if(data.length == 0){
					toastrStyle();
					toastr.warning("请至少选择一条记录！");
				} else {
					for(var i=0;i < data.length;i++){
						idArr[i] = data[i].id;
					}
					$.ajax({
						type:'post',
						url:'${pageContext.request.contextPath }/inventory/deleteInventoryOrderDetailById.do',
						data:{"idArr" : idArr},
						success:function(data){
							layer.confirm('确定删除吗？', function(index){
								if(data > 0){
									toastrStyle();
									toastr.success("删除成功！");
									setTimeout(function(){
										location.reload();
									},1000);
									setTimeout(function(){
										window.location.reload();
									},2000);
								}else{
									toastrStyle();
									toastr.warning("删除失败！");
									location.reload();
								}
							});
						}
					});
				}
			});
			//新增
            $("#add").click(function(){
            	//时间戳
        		var timestamp = (new Date()).getTime();
                layer.open({
                    type: 1 					//Page层类型
                    ,area: ['1000px', '500px'] 	//宽  高
                    ,title: '新增'
                    ,shade: 0.6 				//遮罩透明度
                    ,maxmin: true 				//允许全屏最小化
                    ,anim: 1 					//0-6的动画形式，-1不开启
                    ,content:
                        '<div id="addDivID">'+
							'<form class="layui-form" id="addFormID">'+
								'<xblock>'+
									'<table>'+
										'<tr>'+
											'<td><label class="layui-form-label">盘点单号</label></td>'+
											'<td>'+
												'<input readonly class="layui-input" id="inventory_order_num" name="inventory_order_num" value="PDDH-'+timestamp+'" style="width: 190px; color: gray">'+
											'</td>'+
											'<td><label class="layui-form-label">盘点类型</label></td>'+
											'<td>'+
												'<div style="width: 190px; float: left;">' +
													'<select id="inventory_type" name="inventory_type" lay-verify="inventory_type" lay-filter="inventory_type" style="width: 190px">' +
														'<option value="">请选择盘点类型</option>' +
														'<option value="日盘点">日盘点</option>' +
														'<option value="周盘点">周盘点</option>' +
														'<option value="月盘点">月盘点</option>' +
														'<option value="年盘点">年盘点</option>' +
													'</select>'+
												'</div>'+
			                                    '<div style="margin-top: 12px;">'+
			                                        '<span style="color:red; font-size: 24px; margin-left: 4px">*</span>'+
			                                    '</div>'+
											'</td>'+
											'<td>&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;</td>'+
											'<td>'+
												/* '<div style="width: 190px; float: left;">' +
													'<select id="customer_id" name="customer_id" lay-verify="customer_id" lay-filter="customer_id" style="width: 190px">' +
														'<option value="">请选择盘点物料</option>' +
													'</select>'+
												'</div>'+
												'<div style="margin-top: 12px;">'+
			                                        '<span style="color:red; font-size: 24px; margin-left: 4px">*</span>'+
			                                    '</div>'+ */
			                                    '<button type="button" class="layui-btn" id="btn">请选择盘点的物料</button>'+
											'</td>'+
										'</tr>'+
										/*'<tr align="center">'+
											'<td colspan="2"><button class="layui-btn layui-btn-blue" id="subBtn" lay-submit lay-filter="addForm" style="margin-left:160px; margin-bottom: 20px">提交</button></td>'+
											'<td colspan="2">&emsp;&emsp;&emsp;&emsp;<button type="reset" class="layui-btn layui-btn-primary" style="margin-bottom: 20px">重置</button></td>'+
										'</tr>'+*/
									'</table>'+
								'</xblock>'+
								
								'<table class="layui-table" id="myTable">' +
									'<thead style="text-align: center">'+
										'<tr style="background: #009688; color: white; align: center" >'+
											/* '<th align="center">物料ID</th>'+
											'<th align="center">供应商名称</th>'+
											'<th align="center">物料名称</th>'+
                        					'<th align="center">实际数量</th>'+
											'<th align="center">理论数量</th>'+
											'<th align="center">差异数量</th>'+
											'<th align="center">产品码</th>'+
											'<th align="center">简码</th>'+
											'<th align="center">供应商ID</th>'+ */
											
											'<th style="display:none">物料ID</th>'+
											'<th style="display:none">供应商ID</th>'+
											'<th style="text-align:center;">供应商名称</th>'+
											'<th style="text-align:center;"}">物料名称</th>'+
											'<th style="text-align:center;"}">产品码</th>'+
											'<th style="text-align:center;"}">简码</th>'+
											'<th style="text-align:center;"}">物料规格</th>'+
											'<th style="text-align:center;"}">物料型号</th>'+
											
										'</tr>'+
									'</thead>'+
									'<tbody id="tbody" style="text-align: center;">'+
	                    			'</tbody>'+
								'</table>'+
								'<xblock>'+
									'<button class="layui-btn layui-btn-blue" id="subBtn" lay-submit lay-filter="addForm" style="margin-left:360px; margin-bottom: 10px">提交</button>'+
									'&emsp;&emsp;&emsp;&emsp;<button class="layui-btn layui-btn-primary" style="margin-bottom: 10px">取消</button>'+
								'</xblock>'+
								'</table>'+
							'</form>'+
                    	'</div>'
                    ,success: function(){
                        laydate.render({
                            elem: '#inventory_time1'
                        });
                        form.render();
                    }
                });
			});

			//批量删除
			$("#dels").click(function(){
				var rowData = table.checkStatus('contenttable');
				var data = rowData.data;
				var idArr = new Array();
				if(data.length == 0){
					toastrStyle();
					toastr.warning("请至少选择一条记录！");
				} else {
					for(var i=0;i < data.length;i++){
						idArr[i] = data[i].id;
					}
					$.ajax({
						type:'post',
						url:'${pageContext.request.contextPath }/inventory/deleteInventoryOrderById.do',
						data:{"idArr" : idArr},
						success:function(data){
							layer.confirm('确定删除吗？', function(index){
								if(data > 0){
									toastrStyle();
									toastr.success("删除成功！");
									setTimeout(function(){
										location.reload();
									},1000);
									setTimeout(function(){
										window.location.reload();
									},2000);
								}else{
									toastrStyle();
									toastr.warning("删除失败！");
									location.reload();
								}
							});
						}
					});
				}
			});
			
		
			
			form.on('select(inventory_warehouse)', function(data){
		    	var id = data.value;	//改变后的值
		    	//根据仓库ID获取供应商信息
		    	$.ajax({
	                type: "post",
	                url: "${pageContext.request.contextPath }/cancellingStockManager/getCustomerByWarehouseId.do",
	                data:{"id":id},
	                dataType: 'JSON',
	                async: false,
	                success: function (datas) {
	                	//设置下拉列表中的值的属性
	                    for ( var i = 0; i < datas.length; i++) {
	                    	//增加下拉列表。
	                      	$("#customer_id").append("<option value='"+datas[i].id+"'>"+datas[i].customer_name+"</option>");
	        			}
	                }
	          	});
				form.render();
		    });
			//完毕
			})
		//获取选中产品清单
		function addProduct (){
            var wareId = $('#inventory_warehouse').val();
            var customerId = $('#customer_id').val();
			layer.open({
                type: 1 					//Page层类型
                ,area: ['900px', '450px'] 	//宽  高
                ,title: '产品清单'
                ,shade: 0.6 				//遮罩透明度
                ,maxmin: true 				//允许全屏最小化
                ,anim: 1 					//0-6的动画形式，-1不开启
                ,content: '<form class="layui-form">' +
							   	'<table id="productTable" lay-filter="productTable"></table>' +
						  '</form>'
                ,success: function () {
                    table.render({
                        elem: '#productTable'
                        ,url:'${pageContext.request.contextPath }/cancellingStockDetailManager/listPageMaterielByWarehouseId.do?warehouseId='+wareId+'&customerId'+customerId
                        ,limits:[10,20,30]
                        ,defaultToolbar:['filter', 'print']
                        ,cols: [[
           					{type: 'checkbox', fixed: 'left'}
           					,{field:'xuhao', title:'序号', sort: true, type:'numbers', width: 60}
           					//,{field:'id', title:'物料ID', align:'center', hide:true} //隐藏不显示
           					,{field:'materiel_name', title:'物料名称',templet:function(row){
           						if(row.materiel_name!=null){
           							return row.materiel_name;
           						}else{
           							return "";
           						}
           					}}
           					,{field:'materiel_num', title:'产品码',templet:function(row){
           						if(row.materiel_num!=null){
           							return row.materiel_num;
           						}else{
           							return "";
           						}
           					}}
           					,{field:'brevity_num', title:'简码',templet:function(row){
           						if(row.brevity_num!=null){
           							return row.brevity_num;
           						}else{
           							return "";
           						}
           					}}
           				]]
                        ,page: true
                        ,done : function(){
                            $('th').css({
                                'background-color': '#009688', 'color': '#fff','font-weight':'bold',
                            });
                        }
                    });
                }
            }); 
		}
     //日期格式转换
        function dateToStr(date) {
            var time = new Date(date.time);
            var y = time.getFullYear();
            var M = time.getMonth() + 1;
            M = M < 10 ? ("0" + M) : M;
            var d = time.getDate();
            d = d < 10 ? ("0" + d) : d;
            var str = y + "-" + M + "-" + d;
            return str;
        }
        
      	//日期格式转换
		function date2String(timestamp){
			var d = new Date(timestamp);
			var date = (d.getFullYear()) + "-" + 
		       (d.getMonth() + 1<10?"0"+(d.getMonth() + 1):d.getMonth() + 1) + "-" +
		       (d.getDate()<10?"0"+d.getDate():d.getDate());
			return date;
		}
      	
		function formatDate(time) { 
			var d = new Date(time);
        	var dformat = [ d.getFullYear(),
        	checkTime(d.getMonth() + 1), checkTime(d.getDate()) ].join('-');
        	return dformat;
    	};
    	
   	  	//修改时间戳查询时间
		function checkTime(n) {
			return n < 10 ? '0' + n : n;
   	  	};
	</script>
</body>
</html>
